package de.seminar.lego3D.fragments;

import java.util.ArrayList;
import de.seminar.lego3D.Constants;
import de.seminar.lego3D.R;
import de.seminar.lego3D.colorPicker.ColorPanelView;
import de.seminar.lego3D.colorPicker.ColorPickerView;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * The Fragment that shows the colors the user can choose for the lego bricks.
 * @author Christian Lander
 *
 */
public class BricksColorFragment extends DetailsFragment implements
		View.OnClickListener {

	/** the colors in a gridview **/
	private GridView colorGrid;

	/** adapter for the grid view **/
	private ColorAdapter adapter;

	/** the color picker view **/
	private ColorPickerView colorPickerView;

	/** new color panel **/
	private ColorPanelView newColorPanel;

	/** button to add a color to the list **/
	private Button addColorBtn;

	/** context of this view **/
	private Context ctx;

	/** the current chosen color **/
	int currentColor;

	/** image that holds the animation for the painter **/
	private ImageView painterImg;

	/** the animation drawables **/
	private AnimationDrawable painterMix, painterPaint;

	/**
	 * Create a new instance of LegoBricksFragment, initialized to show the view
	 * at 'index'.
	 */
	public static BricksColorFragment newInstance(int index) {
		BricksColorFragment f = new BricksColorFragment();

		// Supply index input as an argument.
		Bundle args = new Bundle();
		args.putInt("index", index);
		f.setArguments(args);

		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		ctx = getActivity();

		// Inflate the layout for this fragment
		View v = inflater.inflate(R.layout.color_fragment, container, false);

		colorPickerView = (ColorPickerView) v
				.findViewById(R.id.color_picker_view);
		// oldColorPanel = (ColorPanelView)
		// v.findViewById(R.id.old_color_panel);
		newColorPanel = (ColorPanelView) v.findViewById(R.id.new_color_panel);
		addColorBtn = (Button) v.findViewById(R.id.add_color);

		painterImg = (ImageView) v.findViewById(R.id.painterAnim);
		painterImg.setBackgroundResource(R.anim.painter_mixing_anim);
		painterMix = (AnimationDrawable) painterImg.getBackground();

		colorPickerView
				.setOnColorChangedListener(new ColorPickerView.OnColorChangedListener() {

					@Override
					public void onColorChanged(int color) {
						newColorPanel.setColor(color);
						currentColor = color;
					}
				});

		colorGrid = (GridView) v.findViewById(R.id.colorGrid);

		colorGrid.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View v,
					int postiion, long id) {

				Constants.CURRENT_COLOR = Constants.colors.get(postiion);
				if (Constants.CURRENT_LEGO != null) {
					Constants.CURRENT_LEGO.setColor(Constants.CURRENT_COLOR);
				}

				painterMix.stop();
				if (painterPaint != null) {
					painterPaint.stop();
				}

				DetailsFragment settingsFragment = (DetailsFragment) getFragmentManager()
						.findFragmentById(R.id.details_frag);
				if (settingsFragment == null
						|| settingsFragment.getShownIndex() != 0) {
					// Make new fragment to show this selection.
					settingsFragment = LegoBricksFragment.newInstance(0);

					// Execute a transaction, replacing any existing
					// fragment
					// with this one inside the frame.
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					ft.replace(R.id.details_frag, settingsFragment);
					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					ft.commit();
				}
				Constants.CUR_FRAG = 0;
			}
		});

		colorGrid.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> av, View v,
					final int position, long id) {
				AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
				builder.setMessage(
						"Are you sure you want to delete this color?")
						.setCancelable(false)
						.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										Constants.colors.remove(position);
										adapter.notifyDataSetChanged();
										colorGrid.invalidateViews();
									}
								})
						.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
				return true;
			}
		});

		colorPickerView.setColor(0xff000000, true);
		colorPickerView.setAlphaSliderVisible(true);
		colorPickerView.setSliderTrackerColor(0xffCECECE);
		colorPickerView.setBorderColor(0xff7E7E7E);
		newColorPanel.setBorderColor(colorPickerView.getBorderColor());

		addColorBtn.setOnClickListener(this);

		adapter = new ColorAdapter(ctx);
		colorGrid.setAdapter(adapter);

		return v;
	}

	@Override
	public void onResume() {

		painterMix.stop();
		painterMix.start();

		super.onResume();
	}
	
	

	@Override
	public void onStop() {
		
		if (painterMix != null) {
			painterMix.stop();
		}
		
		if (painterPaint != null) {
			painterPaint.stop();
		}
		
		super.onStop();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add_color:
			painterMix.stop();
			if (painterPaint != null) {
				painterPaint.stop();
				painterPaint.start();
			} else {

				painterImg.setBackgroundResource(R.anim.painter_coloring_anim);
				painterImg.requestLayout();
				painterPaint = (AnimationDrawable) painterImg.getBackground();
			}

			painterPaint.start();
			if (!Constants.colors.contains(currentColor)) {
				Constants.colors.add(currentColor);
				adapter.notifyDataSetChanged();
				colorGrid.invalidateViews();
			}
			break;
		}
	}

	/**
	 * Clears the color view, and the array.
	 */
	public void clearColors() {
		Constants.colors.clear();
		adapter.notifyDataSetChanged();
		colorGrid.invalidateViews();
	}

	public void colorChanged(int color) {
	}

	/**
	 * Adapter class to fill the gridview.
	 * 
	 * @author christian
	 * 
	 */
	public class ColorAdapter extends BaseAdapter {

		/**
		 * context of the activity
		 */
		private Context context;

		/**
		 * the default icon of the color drop
		 */
		private Drawable drawableIcon;

		/**
		 * Creates a new adapter.
		 * 
		 * @param c - the context of the activity
		 */
		public ColorAdapter(Context c) {
			context = c;
			drawableIcon = ctx.getResources()
					.getDrawable(R.drawable.color_drop);
		}

		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}

		/**
		 * Returns the number of items in the gridView.
		 */
		public int getCount() {
			return Constants.colors.size();
		}

		/**
		 * Returns an object reference to a specific item.
		 */
		public Object getItem(int position) {
			return Constants.colors.get(position);
		}

		/**
		 * Returns the id of a item at a position
		 */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * Returns the array filled with the colors
		 * 
		 * @return
		 */
		public ArrayList<Integer> getColors() {
			return Constants.colors;
		}

		/**
		 * Sets the color array to the given one and updates the view.
		 */
		public void setColors(Object[] objects) {
			Constants.colors.clear();
			for (Object o : objects) {
				Constants.colors.add((Integer) o);
			}
			adapter.notifyDataSetChanged();
			colorGrid.invalidateViews();
		}

		/**
		 * create a new ImageView for each item referenced by the Adapter
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = LayoutInflater.from(ctx).inflate(R.layout.color_image,
					null, false);
			ImageView img = (ImageView) v.findViewById(R.id.color_view);
			img.setImageResource(R.drawable.color_drop3);
			img.setBackgroundColor(Constants.colors.get(position));
			return v;
		}
	}
}
